package com.aurora.leetcode.answer;

import com.aurora.leetcode.entity.ListNode;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
public class MergeOrderList_21 {
    /**
     * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
     * */
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null || list2 == null){
            return list1!=null?list1:list2;
        }
        ListNode p1 = list1;
        ListNode preP1 = null;
        ListNode p2 = list2;
        while(p1!=null && p2!=null){
            if(p1.val <= p2.val){
                preP1 = p1;
                p1 = p1.next;
            }else{
                if(preP1 == null){
                    list1 = p2;
                }else{
                    preP1.next = p2;
                }
                preP1 = p2;
                p2 = p2.next;
                preP1.next = p1;
            }
        }
        if(p1 == null){
            preP1.next = p2;
        }
        return list1;
    }
}
